<script setup lang="ts">
import { SearchConfig } from './config/search-config';
import { tableConfig } from './config/table-config';
import { editConfig } from './config/edit-config';
import {
    doGetEquipmentList,
    doDelEquipment,
    doUpdateEquipment
} from '@/api/modeling/equipment/index';
import paramsStore from '@/store/modules/paramsStore';
import addDataStore from '@/store/modules/addDataStore';
import { doGetWorkshopList } from '@/api/base/workshop/index';
import { Plus, Delete } from '@element-plus/icons-vue';
import { handleDelKey } from '@/utils';
import type { IWorkshop } from './type';
import type { WorkshopRecords } from '@/api/base/workshop/model/type';
import type { EquipmentData } from '@/api/modeling/equipment/model/type';

defineOptions({
    name: 'EquipmentList'
});

const router = useRouter();
const route = useRoute();
const { handleAddData } = addDataStore();

const tableRef = ref<TableRef>();
const searchRef = ref<SearchRef>();

/**
 * @: 删除相关
 */
const selectIds = ref<number[] | string[]>([]);
const equipmentList = ref<EquipmentData[]>([]);
const handleSelection = (equipments: EquipmentData[]) => {
    equipmentList.value = equipments;
    selectIds.value = equipments.map(item => item.id);
};

// 删除相关
const { handleDel, rowDel } = useDelRow(tableRef, selectIds, doDelEquipment);

/**
 * @: 表格新增
 */
const handleAdd = () => {
    handleAddData('equipmentAddData');
    tableRef.value?.clearSelection();
    router.push('/equipment/add');
};

const mapStatus = {
    IDLE: { text: '空闲', icon: 'zhuangtai-kongxian1' },
    USING: { text: '使用中', icon: 'zhuangtai-qiyong' },
    SCRAP: { text: '报废', icon: 'zhuangtai-baofei' },
    IDLE_SCRAP: { text: '维修中', icon: 'zhuangtai-weixiuzhong' }
};

/**
 * 车间
 */
const loading = ref(false);
const itemCodeOption = ref<WorkshopRecords[]>();
const itemCodeRemoteMethod = async (query: string) => {
    loading.value = true;
    try {
        const { data } = await doGetWorkshopList({ keyword: query, size: 200, current: 1 }, 1);
        if (data) {
            itemCodeOption.value = data.records;
        }
    } catch (error) {
        console.log('-------', error);
    }
    loading.value = false;
};

/**
 * @: 编辑相关
 */
const baseEditRef = ref<EditRef>();
const handleEdit = (row: EquipmentData) => {
    const { workshopName, workshopCode } = row;
    baseEditRef.value?.open({ ...row, workshop: `${workshopName} - ${workshopCode}` });
};

/**
 * @: 处理编辑的提交数据
 */
const handleSubmitData = (row: EquipmentData & IWorkshop) => {
    let data = { ...row };
    if (typeof row.workshop !== 'string') {
        data = { ...row, workshopId: row.workshop.id, workshopName: row.workshop.workshopName };
    }
    const arr = [
        'latestTime',
        'dataSource',
        'creator',
        'createTime',
        'equipmentStatusName',
        'workshopCode',
        'workshop',
        'updateTime'
    ];
    return handleDelKey(data, arr);
};

/**
 * @: 处理搜索
 */
const params = paramsStore();
const { equipmentNumber } = storeToRefs(params);
const searchConfig = computed(() => {
    SearchConfig.items[1].default = equipmentNumber.value;
    return SearchConfig;
});

onActivated(() => {
    initEquipment();
});

/**
 * 初始化设备编码
 */
const initEquipment = () => {
    const code = route.query.code as string;
    if (code) params.setEquipmentNumber(code);
};

const toLink = () => {
    router.push('/Workshop');
    baseEditRef.value?.close();
};
</script>

<template>
    <q-page>
        <base-search
            ref="searchRef"
            :key="equipmentNumber"
            :table-ref="tableRef"
            :search-config="searchConfig"
            @refresh="params.setEquipmentNumber('')"
        />

        <base-table
            ref="tableRef"
            :key="equipmentNumber"
            :table-config="tableConfig"
            :get-data-fn="doGetEquipmentList"
            :added-params="{ equipmentNumber: equipmentNumber }"
            @selection-change="handleSelection"
            @edit="handleEdit"
            @del="rowDel"
        >
            <template #tableHeadStart>
                <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增 </el-button>
            </template>

            <template #tableHeadEnd>
                <el-button
                    class="m-r-16"
                    :disabled="!selectIds.length"
                    :icon="Delete"
                    @click="handleDel(`选中${selectIds.length}行数据，删除后无法恢复，确认删除？`)"
                >
                    删除
                </el-button>
            </template>
            <template #equipmentStatus="{ row }: SlotData<EquipmentData>">
                <div class="align-center">
                    <q-icon
                        size="12"
                        class-name="m-r-8"
                        :icon-class="mapStatus[row.equipmentStatus].icon"
                    />
                    {{ mapStatus[row.equipmentStatus].text }}
                </div>
            </template>
        </base-table>

        <!-- 编辑 -->
        <base-edit
            ref="baseEditRef"
            :edit-config="editConfig"
            :updateFn="doUpdateEquipment"
            :handle-submit-data="handleSubmitData"
            :table-ref="tableRef"
            width="650px"
            column
        >
            <template #workshop="{ row, item, validFn }">
                <el-select
                    v-model="row.workshop"
                    filterable
                    remote
                    :loading="loading"
                    reserve-keyword
                    remote-show-suffix
                    :remote-method="(e: string) => itemCodeRemoteMethod(e)"
                    value-key="id"
                    popper-class="push-select"
                    placeholder="输入关键字查询"
                    @focus="
                        (e: any) => {
                            itemCodeRemoteMethod('');
                            validFn.handleFocus(e, row, {
                                config: item
                            });
                        }
                    "
                    @change="validFn.setValidErrorVisible(false)"
                    @blur="validFn.setValidErrorVisible(false)"
                >
                    <el-option
                        v-for="item in itemCodeOption"
                        :key="item.id"
                        :label="item.workshopName + ' - ' + item.workshopCode"
                        :value="item"
                    />
                    <template #footer>
                        <q-push-button @click="toLink" />
                    </template>
                </el-select>
            </template>
        </base-edit>
    </q-page>
</template>

<style scoped lang="scss">
@include b(align-center) {
    display: flex;
    align-items: center;
}
</style>
